/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.paris5.master2.guitarmaster.service;

import com.paris5.master2.guitarmaster.bean.EcomCartRow;
import com.paris5.master2.guitarmaster.bean.EcomProduct;
import com.paris5.master2.guitarmaster.dao.EcomDao;
import com.paris5.master2.guitarmaster.entity.*;
import com.paris5.master2.guitarmaster.exception.EcomException;
import com.paris5.master2.guitarmaster.exception.EcomValidationException;
import java.util.*;
import javax.ejb.EJB;
import javax.ejb.Stateful;

/**
 *
 * @author mourad
 */
@Stateful(mappedName = "cartE")
public class ServiceCartE implements ServiceCartRemoteE {

    @EJB
    private EcomDao sdao;
    @EJB
    private ServiceAdminRemote serviceAdmin;
    @EJB
    private ServiceCustomerRemote serviceCustomer;
    @EJB
    private ServiceProductRemote serviceProduct;
    @EJB
    private ServiceConvertorRemote serviceConvertor;
    private CartE cart;

    public ServiceCartE() {
        cart = new CartE();
    }

    @Override
    public Collection<EcomCartRow> getCart() {
        Collection<CartRow> cartRows = cart.getCartRowCollection();
        Collection<EcomCartRow> ecomCartRows = new ArrayList<EcomCartRow>();
        for (CartRow cartRow : cartRows) {
            ecomCartRows.add(cartRow.getEcomCartRow());
        }
        return ecomCartRows;
    }

    @Override
    public void add(int idProducType, int quantity) throws EcomValidationException, EcomException {

        ProductType product = (ProductType) sdao.find(ProductType.class, idProducType);
        if (product == null) {
            throw new EcomValidationException("Exception,This product does not exist in base");
        }
        if (quantity > product.getQuantity()) {
            throw new EcomException("this quantity (" + quantity + ") is not available");
        }
        if(this.cart.getStatus()==true){
            throw new EcomException("You have already validated the");
        }
        CartRow cartRow = new CartRow();
        cartRow.setProduct(product);
        cartRow.setQuantity(quantity);
        cartRow.setPrice(product.getPrice());
        this.cart.addCartRow(cartRow);
    }

    @Override
    public void remove(int idProductType) throws EcomValidationException, EcomException {
        CartRow cartRow = this.cart.getCartRow(idProductType);
        this.cart.removeCartRow(cartRow);

    }

    @Override
    public void validate(int idUser) throws EcomValidationException, EcomException {
        if(this.cart.getCartRowCollection().isEmpty()){
            throw new EcomException("Your cart is empty");
        }
        this.setUser(idUser);
        float amount = this.getTotalPrice();
        if (this.cart.getUser().getBalance().compareTo(amount) < 0) {
            throw new EcomException("Exception: User does not have enough money");
        }
        Date now = new Date();
        this.cart.setDateCrea(now);
        this.cart.setDateUp(now);
        this.cart.setAmount(amount);
        this.cart.setStatus(Boolean.TRUE);
        sdao.insert(this.cart);
        serviceCustomer.withdrawUserBalance(idUser, amount);
        Iterable<CartRow> cartRows = this.cart.getCartRowCollection();
        for (CartRow cartRow : cartRows) {
            cartRow.setCart(cart);
            sdao.insert(cartRow);
            ProductType productType = cartRow.getProduct();
            List<EcomProduct> products = serviceProduct.getProductByProductType(productType.getIdProductType(), 0, productType.getQuantity());
            serviceProduct.withdrawQuantity(productType.getIdProductType(), cartRow.getQuantity());
            if (products != null)
            {
                Iterator<EcomProduct> iProducts = products.iterator();
                while (iProducts.hasNext()) {
                    EcomProduct ecomProduct = iProducts.next();
                    int idStore = ecomProduct.getStore().getIdStore();
                    Store store = (Store) sdao.find(Store.class, idStore);
                    serviceAdmin.depositAmount(store.getEcomStore(), cartRow.getPrice());
                    Product product = (Product) sdao.find(Product.class, ecomProduct.getIdProduct());
                    product.setStatus(1);
                    sdao.update(product);
                }
            }          
        }
        this.reset();
        cart.setStatus(Boolean.TRUE);
    }

    @Override
    public void reset() {
        this.cart.getCartRowCollection().clear();
    }

    @Override
    public Float getTotalPrice() {
        float amount = 0;
        Iterable<CartRow> cartRows = this.cart.getCartRowCollection();
        for (CartRow cartRow : cartRows) {
            amount += (cartRow.getPrice()*cartRow.getQuantity());
        }
        return amount;
    }

    @Override
    public String getStatus() {
       String status;
       if(this.cart.getCartRowCollection().isEmpty()){
           status="EMPTY";
       }else{
           if(this.cart.getStatus()==true){
           status="BOUGHT";
           }else{
               status="FILLING";
           }         
       }
       return status;
    }

    @Override
    public void setCurrency(String currency)throws EcomException {
        this.cart.setRateCurrency(currency);
        float rate=1;
        rate=(float)serviceConvertor.getRate("EUR", currency); 
        this.cart.setRate(rate);
    }

    @Override
    public float getRate() {
        return this.cart.getRate();
    }

    @Override
    public String getCurrency() {
        return this.cart.getRateCurrency();
    }

    @Override
    public void setUser(int idUser) throws EcomException {
        
        User user=(User)sdao.find(User.class, idUser);
        if (user == null) {
            throw new EcomException("Exception, User no logged");
        }
        this.cart.setUser(user);
        this.setCurrency(user.getCode().getDevise());
    }
    
}
